package com.wzdigit.wms.wms.http;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.framework.Shift;
import com.wzdigit.framework.utils.RedisUtil;
import com.wzdigit.wms.basic.domain.dtos.inventory.UpdateInventoryInputDto;
import com.wzdigit.wms.basic.domain.inventory.Goods;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsMapper;
import com.wzdigit.wms.basic.service.code.InventoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Component;


import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 企业微信消息推送服务
 * Created by zyf on 2021/11/5 17:33
 */
@Component
@Slf4j
public class ChatHttpClient {

    private static final String key="key";
   // private static final String corpId="ww3a201a45007d1799";
    private static final String corpId="ww49bc7771253b25f9";
    //private static final String secret="yfZCqzMkQlmEbOwnvwue4q3PY8seiZGvPdaEvKXJOu0";
    private static final String secret="CjxRztbAsyUNwpGMNnkA-NI29QQLy-8X_7XQGuMw3EQ";

    private static final String tokenUrl="https://qyapi.weixin.qq.com/cgi-bin/gettoken";
    private static final String sendUrl="https://qyapi.weixin.qq.com/cgi-bin/message/send";

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private InventoryService inventoryService;

    //推送消息
    public String send(List<String> userIds,Integer agentId,String contentText) throws Exception{
        //获取token
        String token = getToken2();
        String userStr = String.join("|", userIds);

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        CloseableHttpResponse closeableHttpResponse = null;

        String url=sendUrl+"?access_token="+token;
        JSONObject params = new JSONObject();
        params.put("touser",userStr);
        JSONObject textJson = new JSONObject();
        textJson.put("content",contentText);
        params.put("msgtype", "text");
        params.put("text",textJson);
        params.put("agentid",agentId);
        String contractParam = params.toString();
        try {
            log.info("消息推送开始:"+contractParam);
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
            StringEntity entity = new StringEntity(contractParam , ContentType.create(ContentType.APPLICATION_FORM_URLENCODED.getMimeType(), "UTF-8"));
            httpPost.setEntity(entity);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpPost.setConfig(requestConfig);
            closeableHttpResponse = closeableHttpClient.execute(httpPost);
            String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
            log.info("消息推送:"+responseString);
            //解析返回的JSON
            JSONObject jsonObject = new JSONObject(responseString);
            String errMsg = jsonObject.getString("errmsg");
            if (!"ok".equals(errMsg)){
                Shift.fatal("请求企业微信api失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal("请求企业微信api失败!");
        }
        return "发送成功";
    }

    //获取token
    public String getToken(){
        String token = getTokenCahe();
        if (token!=null){
            return token;
        }
        //调企业微信获取token接口
        log.info("获取企业微信token");
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建HttpGet对象，设置url访问地址
        HttpGet httpGet=new HttpGet();
        try {
            URIBuilder uriBuilder=new URIBuilder(tokenUrl);
            uriBuilder.setParameter("corpid",corpId);
            uriBuilder.setParameter("corpsecret",secret);
            httpGet= new HttpGet(uriBuilder.build());
        }catch (Exception e){
            e.printStackTrace();
            Shift.fatal("构建HTTP请求失败!");
        }

        CloseableHttpResponse response = null;
        try {
            //使用HttpClient发起请求，获取response
            response = httpClient.execute(httpGet);

            //解析响应
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                log.info(content);
                //开始解析json
                JSONObject jsonObject = new JSONObject(content);
                token = jsonObject.getString("access_token");
                insertUpdateTokenCache(token);
            }

        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal("获取企业微信Token失败");
        }finally {
            //关闭response
            try {
                response.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
                Shift.fatal("获取企业微信Token失败");
            }

        }

        return token;
    }

    //获取token
    public String getToken2(){
        String token=null;
        token = getTokenCahe();
        if (token!=null){
            return token;
        }
        //调企业微信获取token接口
        log.info("获取企业微信token");
        String url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + corpId + "&corpsecret=" + secret;
        try {
            URL urlObject = new URL(url);
            HttpsURLConnection connection = (HttpsURLConnection) urlObject.openConnection();
            BufferedReader in = null;
            StringBuilder result = new StringBuilder();
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            if (in != null) {
                in.close();
            }
            log.info("获取企业微信token接口返回结果:"+result);
            JSONObject jsonObject = new JSONObject(result.toString());
            String errmsg = jsonObject.getString("errmsg");
            if (!"ok".equals(errmsg)){
                Shift.fatal("获取企业微信token接口失败");
            }
            token = jsonObject.getString("access_token");
            insertUpdateTokenCache(token);
        }catch (Exception e){
            e.printStackTrace();
            Shift.fatal("获取企业微信token接口失败");
        }
        return token;
    }

    private String getTokenCahe(){
        String token=(String) RedisUtil.get(key);
        return token;
    }

    public void insertUpdateTokenCache(String token){
        //过期时间设置<2h
        RedisUtil.set(key,token,7000);
    }

    public void deleteTokenCache(){
        RedisUtil.delete(key);
    }

    //测试，获取用户userid
    public String test() throws Exception{
        //获取token
        String token = getToken();

        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        CloseableHttpResponse closeableHttpResponse = null;

        String url="https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token="+token;
        Map<String,String> map = new HashMap<>();
        map.put("mobile","13750457819");
        String contractParam = JSON.toJSONString(map);

        try {
            log.info("消息推送开始");
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
            StringEntity entity = new StringEntity(contractParam , ContentType.create(ContentType.APPLICATION_FORM_URLENCODED.getMimeType(), "UTF-8"));
            httpPost.setEntity(entity);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpPost.setConfig(requestConfig);
            closeableHttpResponse = closeableHttpClient.execute(httpPost);
            String responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");
            log.info("获取用户id:"+responseString);
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal("请求企业微信api失败!");
        }
        return "发送成功";
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void testinv() throws Exception{
        Goods goods = goodsMapper.selectOne(new QueryWrapper<Goods>().eq("GOODS_SN", "11941WL4001L41200081"));
        UpdateInventoryInputDto fmInv=new UpdateInventoryInputDto();
        fmInv.setLocId(1034);
        fmInv.setWhsId(1025);
        fmInv.setSkuId(3252753);
        fmInv.setQty(goods.getQty());
        fmInv.setOperator("61admin");
        fmInv.setQaStatus(1);
        fmInv.setUnit("PCS");
        fmInv.setOwner(10001);
        fmInv.setFactory("5500");


        inventoryService.invQtyValidation(fmInv,0);

        System.out.println("XXXXXXXXXXXXXXX");

        Thread.sleep(10000);

        inventoryService.updateLocInventroy(fmInv);
        Thread.sleep(10000);

        System.out.println("XXXXXXXXXXXXXXXXXX");
        return;
    }

}
